DROP PROCEDURE [dbo].[pr0364]
GO
---- Xu ly ton kho

CREATE  PROCEDURE [dbo].[pr0364] @DivisionID varchar(20), 	
				@TranMonth as int, 
				@TranYear as int,
				@NextMonth as int, 
				@NextYear int
 AS


Declare @Balance_Cursor as Cursor,
	@InventoryID as varchar(20), 
	@WareHouseID as varchar(20),   
	@InventoryAccountID as varchar(20),  
	@ActBegQty as Money,   
	@ActBegTotal as Money ,         
	 @BookBegQty as Money,
	  @BookBegTotal   as Money


Set @Balance_Cursor = Cursor Scroll KeySet FOR 
	Select	 InventoryID, WareHouseID,   InventoryAccountID, 
		EndQuantity,   EndAmount  
	From	tb0106
	Where 		TranMonth = @TranMonth And 
			 TranYear = @TranYear And  
			DivisionID = @DivisionID

	Open	@Balance_Cursor

	Fetch Next From @Balance_Cursor Into @InventoryID, @WareHouseID,    @InventoryAccountID, 
		@ActBegQty,   @ActBegTotal 
	While @@Fetch_Status = 0
	Begin
		IF  exists (Select 1 From tb0106  Where 	TranMonth = @NextMonth and
							TranYear = @NextYear and
							DivisionID = @DivisionID and
							InventoryID = @InventoryID and
							WareHouseID =@WareHouseID and
							InventoryAccountID =  @InventoryAccountID)
		   Update  tb0106 
			Set 	BeginQuantity = @ActBegQty,
				BeginAmount = @ActBegTotal,
				EndQuantity =@ActBegQty + DebitQuantity - CreditQuantity,
				EndAmount = @ActBegTotal + DebitAmount - CreditAmount 				
			 Where TranMonth = @NextMonth and
				TranYear = @NextYear and
				DivisionID = @DivisionID and
				InventoryID = @InventoryID and
				WareHouseID =@WareHouseID and
				InventoryAccountID =  @InventoryAccountID
		else
		Insert 	tb0106 	(InventoryID,WarehouseID,TranMonth,TranYear,DivisionID, 
					BeginQuantity, BeginAmount, EndQuantity, EndAmount, 
					DebitQuantity, DebitAmount, CreditQuantity, CreditAmount,
					 InventoryAccountID)
		Values (@InventoryID,@WareHouseID,@NextMonth,@NextYear,@DivisionID, 
			@ActBegQty, @ActBegTotal, @ActBegQty, @ActBegTotal,  
			0,0,0,0,	  
			@InventoryAccountID)	
					
						
		Fetch Next From @Balance_Cursor Into @InventoryID, @WareHouseID,    @InventoryAccountID, 
		@ActBegQty,   @ActBegTotal 
	End
	
	Close @Balance_Cursor


GO